﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Arizu.Repository;
using System.Data;
using Arizu.Entity;

namespace AiRiZu.User.handler
{
    public class EditCalendar : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Params["roomId"] == null || string.IsNullOrEmpty(context.Request.Params["roomId"]))
            {
                return;
            }

            try
            {
                long roomId = long.Parse(context.Request.Params["roomId"].ToString());
                string checkin = context.Request.Params["startDate"].ToString();
                string checkout = context.Request.Params["endDate"].ToString();
                int advancedPricing = int.Parse(context.Request.Params["price"].ToString());
                int state = bool.Parse(context.Request.Params["unavailable"].ToString()) ? 1 : 0;

                AirizuCalendar airizuCalendar = AirizuCalendar.CreateInstance();
                DateTime checkinDate = DateTime.ParseExact(checkin.Replace("/", ""), "MMddyyyy", null);
                DateTime checkoutDate = DateTime.ParseExact(checkout.Replace("/", ""), "MMddyyyy", null);

                DataTable dt = airizuCalendar.GetCalendars(roomId, checkinDate.Ticks, checkoutDate.Ticks);
                if (dt.Rows.Count == 0)
                {
                    CalendarEntity entity = new CalendarEntity();
                    entity.RoomID = roomId;
                    entity.StartTime = checkinDate.Ticks;
                    entity.EndTime = checkoutDate.Ticks;
                    entity.State = state;
                    entity.Price = advancedPricing;
                    airizuCalendar.Insert(entity);
                }
                else
                {
                    airizuCalendar.UpdateCalendar(roomId, state, advancedPricing, checkinDate.Ticks, checkoutDate.Ticks);
                }

                context.Response.Write("success");
            }
            catch (Exception)
            {

                context.Response.Write("error");
            }
        } 

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
